package Demo1_17;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User：Lenovo
 * Date:2025-01-17
 * Time:20:04
 */
//给你一个链表的头节点 head 和一个整数 val ，请你删除链表中所有满足 Node.val == val 的节点，并返回 新的头节点 。
class ListNode {
    int val;
    ListNode next;
    ListNode(int val) {
        this.val = val;
    }
}

class RemoveElements {
    public ListNode removeElements(ListNode head, int val) {
        // 处理头节点值等于 val 的情况
        while (head!= null && head.val == val) {
            head = head.next;
        }
        ListNode curr = head;
        while (curr!= null && curr.next!= null) {
            if (curr.next.val == val) {
                curr.next = curr.next.next;
            } else {
                curr = curr.next;
            }
        }
        return head;
    }

    public static void main(String[] args) {
        // 创建链表 1 -> 2 -> 6 -> 3 -> 4 -> 5 -> 6
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(6);
        head.next.next.next = new ListNode(3);
        head.next.next.next.next = new ListNode(4);
        head.next.next.next.next.next = new ListNode(5);
        head.next.next.next.next.next.next = new ListNode(6);

        RemoveElements solution = new RemoveElements();
        int valToRemove = 6;
        ListNode newHead = solution.removeElements(head, valToRemove);
        // 打印删除元素后的链表
        ListNode temp = newHead;
        while (temp!= null) {
            System.out.print(temp.val + " ");
            temp = temp.next;
        }
    }
}
